package com.example.market.controller;

import com.example.market.pojo.Product;
import com.example.market.service.ProductService;
import com.example.market.util.JsonResponse;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {
    private JsonResponse jsonResponse;
    private ProductService productService;

    @Autowired
    public void setJsonResponse(JsonResponse jsonResponse) {
        this.jsonResponse = jsonResponse;
    }

    @Autowired
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping("/{productId}")
    public JsonResponse getProduct(@PathVariable String productId) {
        Product product = productService.getProductById(productId);
        jsonResponse.success("001", product);
        return jsonResponse;
    }

    @GetMapping("/category/limit/{categoryId}")
    public JsonResponse getProductByCategoryId(@PathVariable Integer categoryId) {
        List<Product> list = productService.getProductByCategoryId(categoryId);
        jsonResponse.success("001", list);
        return jsonResponse;
    }

    @GetMapping("/category/hot")
    public JsonResponse getHotProduct() {
        List<Product> list = productService.getHotProduct();
        jsonResponse.success("001", list);
        return jsonResponse;
    }

    @GetMapping("/page/{currentPage}/{pageSize}/{categoryId}")
    public Map<String, Object> getProductByPage(@PathVariable String currentPage, @PathVariable String pageSize, @PathVariable String categoryId) {
        List<Product> productList = productService.getProductByPage(currentPage, pageSize, categoryId);
        Integer total = productService.getTotal(categoryId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", "001");
        map.put("data", productList);
        map.put("total", total);
        return map;
    }

    @PostMapping("/getProductBySearch/{search}/{currentPage}/{pageSize}")
    public Map<String, Object> getProductBySearch(@PathVariable String search, @PathVariable String currentPage, @PathVariable String pageSize) {

        List<Product> productList = productService.getProductBySearch(search, currentPage, pageSize);
        int total = productService.searchCount(search);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", "001");
        map.put("data", productList);
        map.put("total", total);
        return map;
    }
}
